package com.douwong.student.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.douwong.student.R;
import com.douwong.student.adapter.MicroAdapter;
import com.douwong.student.adapter.MicroListTask;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.db.PrepareReaourceDBService;
import com.douwong.student.interfaces.WorkResultNotify;
import com.douwong.student.model.PrepareResource;
import com.douwong.student.model.RequestAction;
import com.douwong.student.task.PrepareListTask;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.JsonUtils;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.view.PullToRefreshListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/*
预习里面的微课
 */
public class MicroFragment extends Fragment {
	private View view;
	private PullToRefreshListView prepare_listview;
	private MicroAdapter adapter;
//	private PrepareClassActivity activity;
	private BaseApplication app;
	private ArrayList<PrepareResource> list;
	private boolean isRefreshing = false;
	private int visibleLastIndex = 0, currentPageIndex = 1;
	private MediaPlayer player;
	private final static String TAG="MicroFragment";

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		app = (BaseApplication) activity.getApplication();
//		activity=(PrepareClassActivity)activity;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.micro_layout, null);
		prepare_listview = (PullToRefreshListView) view.findViewById(R.id.micro_listview);
		prepare_listview.setOverScrollMode(View.OVER_SCROLL_NEVER);
		list = new ArrayList<PrepareResource>();
		adapter = new MicroAdapter(getActivity(), list);
		prepare_listview.setAdapter(adapter);
		updateData(RequestAction.INIT, 1);
/*		prepare_listview.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				prepare_listview.onScrollStateChanged(view, scrollState);
				if (isRefreshing) {
					return;
				}

				int lastItemIndex = adapter.getCount();
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastItemIndex) {//判读上拉加载更多

					if (30 * (currentPageIndex) <= adapter.getCount()) {
						++currentPageIndex;
						updateData(RequestAction.LOADMROE, currentPageIndex);
						isRefreshing = true;
					}
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				prepare_listview.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
				Log.e("开始刷新", "开始刷新");
				visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
			}
		});*/

		prepare_listview.setOnILoadMoreListener(new PullToRefreshListView.OnILoadMoreListener() {
			@Override
			public void onLoadMore() {
				//
				if (isRefreshing) {
					return;
				}
				++currentPageIndex;
				updateData(RequestAction.LOADMROE, currentPageIndex);
				isRefreshing = true;

			}
		});
		prepare_listview.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {

			@Override
			public void onRefresh() {
				updateData(RequestAction.REFRESH, 1);
			}
		});
		prepare_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,final int arg2, long arg3) {
				if (list.get(arg2 - 1).getDownLoadUrl() != null && !list.get(arg2 - 1).getDownLoadUrl().equals("")) {

					new AlertDialog.Builder(getActivity()).setItems(new String[]{"在线观看","下载"}, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if(0==which){
								try {
									if (NetUtils.NetwrokIsUseful(getActivity())) {
										Intent intent = new Intent(Intent.ACTION_VIEW);
//										String type = "video*//*";
										String type= FileUtils.getMIMEType(list.get(arg2-1).getFileSuffix());
										Uri uri = Uri.parse(list.get(arg2 - 1).getDownLoadUrl());
										intent.setDataAndType(uri, type);
										startActivity(intent);
									} else {
										Toast.makeText(getActivity(), "网络未连接", Toast.LENGTH_LONG).show();
									}
								} catch (Exception e) {
									e.printStackTrace();
									Toast.makeText(getActivity(), "播放异常", Toast.LENGTH_LONG).show();
								}
							}else{
								PrepareResource resource=list.get(arg2-1);//下载
								if(PrepareReaourceDBService.getInstance(getActivity()).query(resource.getId())==null){
									resource.setAttaSuffix(resource.getFileSuffix().substring(1));

//									resource.setFileName(resource.getMcTitle());
									LogUtils.i(TAG,"wei ke biao title"+resource.getMcTitle());
									//设置title的值
									resource.setMcTitle(resource.getMcTitle());
									resource.setLoading(true);
									resource.setFilePath(FileUtils.RESOURCE_DIR
											+ resource.getFileName());
									Intent intent = new Intent();
									intent.setAction(CommonConfig.GET_RESOURCE_LOAD);
									intent.putExtra("resource",
											JsonUtils.serialize(resource));
									getActivity().sendBroadcast(intent);
									//更新资源
									PrepareReaourceDBService.getInstance(getActivity()).upDate(resource);
									Toast.makeText(getActivity(), "已加入下载列表中", Toast.LENGTH_LONG).show();
								}else{
									Toast.makeText(getActivity(), "已经在下载列表中", Toast.LENGTH_LONG).show();
								}

							}
						}
					}).create().show();

				} else {
					Toast.makeText(getActivity(), "资源地址异常", Toast.LENGTH_LONG).show();
				}
			}
		});
		return view;
	}

	protected void updateData(final RequestAction action, final int pageIndex) {

		MicroListTask task = new MicroListTask(action, app);
		task.setWorkStautsListener(new WorkResultNotify<PrepareResource>() {


			@Override
			public void notify(int stateCode, List<PrepareResource> arryResult) {

				LogUtils.i(TAG,"这时的stateCode  :  "+stateCode+"RequestAction : "+action+"_____________arryResult : "+((arryResult==null)?0:arryResult.size())+"_____pageIndex  : "+ pageIndex);

				if (PrepareListTask.NO_DATA == stateCode) {

					// 加载更多时，出现异常或者没有多余数据，要将currentPageIndex回到加载数据前的一页
					if (currentPageIndex > 1 && RequestAction.LOADMROE == action) {
						--currentPageIndex;
					}
					if (arryResult == null) {
						//list.clear();
						ToastUtils.makeText(BaseApplication.mContext,"没有更多数据了");
					}

				} else if (PrepareListTask.REQUESTOK == stateCode) {
					// 其他访问类型均需要清空当前数据，重新显示，加载更多是在原有的数据上增加
					if (RequestAction.LOADMROE != action) {
						list.clear();
					}
					if (arryResult != null) {
						list.addAll(arryResult);
						Collections.sort(list);
					}
				} else if (PrepareListTask.NO_NETWOK == stateCode) {
					ToastUtils.makeText(BaseApplication.mContext,"请检查网络");

				}
				isRefreshing = false;
				prepare_listview.onRefreshComplete();
				prepare_listview.completeLoadMore();
				adapter.notifyDataSetChanged();
			}
		});
		if (BaseApplication.sUserBean == null) {
			isRefreshing = false;
			prepare_listview.onRefreshComplete();
			Toast.makeText(getActivity(), R.string.login_please, Toast.LENGTH_LONG).show();
		} else {
			task.execute(String.valueOf(pageIndex));
		}
	}
}
